<template>
	<view class="page">
		<view class="page">
			
			<!-- 消息弹窗 -->
			<quick-message ref="message"></quick-message>
			
			<view class="page-head" :style="{'marginTop': statusBarHeight+'px'}">
				<view class="page-head-left">
					<label class="iconfont icontime"></label>
					{{time.toFixed(1)}}
				</view>
				<view class="page-head-centre">
					<!-- <label class="iconfont iconxiaolian1" @longpress="cheat()"></label> -->
					<label class="iconfont iconxiaolian1"></label>
					{{((complete/((colum*colum)-bombs.length))*100).toFixed(0)}}%
				</view>
				<view class="page-head-right">
					<label class="iconfont iconzhadan"></label>
					{{bombs.length}}
				</view>
			</view>
			<view class="page-body">
				<movable-area style="background-color: #bebebe;overflow: hidden;">
					<!--  -->
					<movable-view
					:style="{
						'marginLeft': (screenWidth/2)-(16*colum) +'px',
						'marginTop': (screenHeight*5/12)-(16*colum)+'px',
						'width': (32*colum) +'px',
						'height': (32*colum) +'px',
					}"
					:direction="colum > 10 ? 'all' : ''"
					@scale="onScale" 
					scale 
					scale-min="0.8" 
					scale-max="2" 
					:scale-value="scale">
					
						<view
						class="page-block" 
						v-for="(i,index) in array" 
						:key=index
						@click="tap(index)"
						@longpress="flag(index)"
						style="border: 1px solid;"
						:style="{
							'width': 30 + 'px', 
							'height': 30 + 'px',
							'line-height': 30 + 'px',
							'backgroundColor': i.type == 'none' ? '#d8d8d8' : ' rgba(0,0,0,0)'
						}"
						>
							
							<image
							v-if="i.type == 'flag'"
							class="block-img"
							:style="{
								'width': 30 +'px',
								'height': 30 +'px',
								}"
							src="../../static/flag.png" 
							mode="">
							</image>
							
							<text v-if="i.type == 'none' && i.text == 0 "></text>		
							
							<image
							v-if="i.type == 'none' && i.text == '炸' "
							class="block-img"
							:style="{
								'width': 30 +'px',
								'height': 30 +'px',
								}"
							src="../../static/bomb.png" 
							mode="">
							</image>
							
							<text v-if="i.type == 'none' && i.text != '炸' && i.text != 0">{{i.text}}</text>
								
						</view>	
					</movable-view>
				</movable-area>
			</view>
			
			
			<view class="page-bottom">
				<view class="page-bottom-left" @click="toSetting()">
					<label class="iconfont iconcaidan"></label>
				</view>
				<view class="page-bottom-centre">
					<button type="primary" @click="Init()">重新开始</button>
					<!-- <button type="primary" @click="removepop(saolei.id)">重新开始</button> -->
				</view>
				<view class="page-bottom-login">
					<button type="primary" @click="toLogin()">
						{{isLogin ? "查看排名" : "登录游戏"}}
					</button>	
				</view>
				<view class="page-bottom-right">
					<!-- <button type="primary" @click="exit()">退出游戏</button>					 -->
					<button type="primary" @click="toHelp">游戏帮助</button>					
					<!-- <button type="primary" @click="toUpdate">退出游戏</button>					 -->
				</view>
			</view>
			
			<updatePhone ref="updatePhone"></updatePhone>
			
		</view>
	</view>
</template>

<script>
	
	import utils from '../../common/util.js'
	var _self
	var lastPopTime = 0
	var lastCancelTime = 0
	
	export default {
		data() {
			return {
				screenHeight: uni.getSystemInfoSync().screenHeight,
				screenWidth: uni.getSystemInfoSync().screenWidth,
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				array: [], // 列表
				bombs: [], // 炸弹列表
				complete: 0, // 完成的个数
				colum: this.$store.state.new_colum, // 边长
				bombNumber: this.$store.state.bombNumber, // 炸弹数量
				isFail: false, // 是否已经失败 进入查看状态
				scale: 1,
				time: 0,
				name: '',
				isLogin : false, // 是否登录
				saolei: {},
				grade: {},
				nowVersion: "", // 当前版本
				nowName: "", // 当前软件名字
				type: this.$store.state.new_model
			}
		},
		onNavigationBarButtonTap(e) {},
		onLoad(data) {
			_self = this
			
			plus.runtime.getProperty(plus.runtime.appid,inf =>{
				_self.nowVersion = parseInt(inf.version.replace('.',"").replace('.',""))
				_self.nowName = inf.name
				_self.$nextTick(function(){
					_self.checkUpdate()
				})
			})
			
			// 判断是否登录
			var userInfo =  uni.getStorageSync("saolei_userInfo")
			if(userInfo){
				_self.saolei = userInfo
				_self.isLogin = true
			}else {
				// 判断是不是跳转过来的
				uni.showModal({
				    title: '当前未登录',
				    content: '登录可上传成绩并查看自己的实时排名哦 ( ง⁼̴̀ω⁼̴́)ง⁼³₌₃ ',
					cancelText:"就不 o(´^｀)o ",
				    success: function (res) {
				        if (res.confirm) {
				            console.log('用户点击确定');
							uni.navigateTo({
								url:'../addAndRegister/addAndRegister',
								animationDuration:400,
								animationType:"slide-in-bottom"
							})
				        }
				    }
				});
			}
			
			this.$nextTick(function(){
				_self.saolei.type = _self.type
				this.Init()
			})
			
		},
		beforeDestroy() {
			// 清除定时任务
			_self.$store.commit("clearTimeId")
		},
		onShow() {
			utils.setUserPkStatus("false")
			//打开webSocket
			utils.closeSocket()
			setTimeout(function(){
				utils.connectSocketInit()
			},500)
		},
		beforeDestroy() {
			// utils.closeSocket()
		},
		methods: {
			checkUpdate(){
				// 获取最新版本
				uni.request({
					url: _self.utils.basicUrl+"/saoleiVersion/lastest",
					method: "GET",
					data: {
						name: _self.nowName
					},
					success: function(res) {
						if(res.data.code === 20000){
							// console.log(res.data.data)
							if(parseInt(res.data.data.versionCode.replace('.',"").replace('.',"")) > _self.nowVersion){
								// console.log("有新版")
								var updateData = res.data.data
								updateData.description = res.data.data.description.split("*")
								_self.$refs.updatePhone.show(updateData)
							}
						}else{
							_self.utils.requestFail(res)
							// uni.showToast({
							// 	icon:"none",
							// 	title: res.data,
							// 	position:"center"
							// })
						}
					},
					fail: () => {
						uni.showToast({
							icon:"none",
							title: '网络错误(⊙ˍ⊙)',
							position:"center"
						})
					},
					complete() {
					}
				})
				// this.$refs.updatePhone.show()
			},
			//更新完成
			getFinshUpdate(e){
				console.log(e)
			},
			Init(){
				_self.complete = 0
				_self.isFail = false
				_self.time = 0
				
				// 清除定时任务
				_self.$store.commit("clearTimeId")
				
				
				_self.array = []
				for (var i = 0; i < this.colum*this.colum; i++) {
					var item = {}
					item.type = 'shade' // 是否遮罩
					item.text = ""
					// if(this.bombs.indexOf(i) == -1){
					// 	item.text = utils.calculateBombNumber(i,this.colum,this.bombs)
					// }else{
					// 	item.text = '炸'
					// }
					
					_self.array.push(item)
					
				}
			},
			
			// 初始化炸弹
			initBombs(id){
				
				// 保证当前点击的id不在雷区
				do{
					_self.bombs = utils.produceRandomNum(_self.bombNumber, (_self.colum*_self.colum-1))
				}while(_self.bombs.indexOf(id) !== -1)
				
				// 修改现有的方格
				for (var i = 0; i < _self.colum*_self.colum; i++) {
					var item = {}
					item.type = 'shade' // 是否遮罩
					// item.text = i
					if(_self.bombs.indexOf(i) === -1){
						item.text = utils.calculateBombNumber(i,_self.colum,_self.bombs)
					}else{
						item.text = '炸'
					}
					_self.array.splice(i,1,item)
				}
			},
			
			exit(){
				 if (plus.os.name.toLowerCase() === 'android') {
					 plus.runtime.quit();
				 }
				 else{ 
					 const threadClass = plus.ios.importClass("NSThread");
					 const mainThread = plus.ios.invoke(threadClass, "mainThread");
					 plus.ios.invoke(mainThread, "exit");
				 }
			},
			
			// 作弊
			cheat(){
				
				if(_self.isFail){
					return
				}
				
				var cheats = []
				for (var i = 0; i < _self.array.length; i++) {
					if(_self.array[i].text == '炸' && _self.array[i].type != "none" && _self.array[i].type != "flag" ){
						cheats.push(i)
						var item = _self.array[i]
						item.type = 'none'
						_self.array.splice(i,1,item)
					}
				}
				
				setTimeout(function(){
					cheats.forEach(ct => {
						var item = _self.array[ct]
						item.type = 'shade'
						_self.array.splice(ct,1,item)
					})
				},500)
				
			},
			
			toSetting(){
				uni.navigateTo({
					url:"../setting/setting",
					animationType:"slide-in-bottom",
					animationDuration:400
				})
			},
			
			toLogin(){
				if(_self.isLogin){
					// 查看排名
					uni.navigateTo({
						url:'../me/me',
						animationType:"slide-in-bottom",
						animationDuration:400
					})
				}else{
					// 登录
					uni.navigateTo({
						url:'../me/me',
						animationType:"slide-in-bottom",
						animationDuration:400
					})
				}
			},
			toHelp(){
				uni.navigateTo({
					url:"../help/help",
					animationType:"slide-in-bottom",
					animationDuration:400
				})
			},
			onChange: function(e) {
				this.old.x = e.detail.x
				this.old.y = e.detail.y
			},
			onScale: function(e) {
				this.scale = e.detail.scale
				// this.old.scale = e.detail.scale
			},
			
			flag(id){
				if(_self.isFail){
					return
				}
				
				var item = this.array[id]
				if(item.type == 'none'){
					return
				}
				item.type = 'flag'
				this.array.splice(id,1,item)
			},
			
			tap(id){
				
				if(_self.isFail){
					return
				}
				
				var item = this.array[id]
				
				if(_self.complete == 0){
					console.log('打开定时器')
					// 刚开始 打开计时器
					var timeId = setInterval(function(){
						_self.time += 0.1
					},100)
					
					this.$store.commit("setTimeId",timeId)
					    
					// 初始化炸弹
					_self.initBombs(id)
				}
				
				// 重新赋值
				item = this.array[id]
				
				if(item.type == 'flag'){
					// 取消标记
					item.type = 'shade'
					this.array.splice(id,1,item)
					return
				}
				
				item.type = 'none'
				this.array.splice(id,1,item)
				this.$nextTick(async function(){
					if(item.text == "炸"){
						await this.$store.commit("clearTimeId")
						setTimeout(function(){
							_self.time= 0
						},500)
						_self.array.forEach(ar => {
							ar.type = 'none'
						})
						
						
						uni.showModal({
						    title: '挑战失败  ᶘ ᵒᴥᵒᶅ  ',
						    content: '请选择是否继续',
							cancelText:"查看",
						    success: function (res) {
						        if (res.confirm) {
						            console.log('用户点击确定');
									_self.Init()
						        } else if (res.cancel) {
									// 清除所有遮罩
									_self.array.forEach(ar => {
										ar.type = 'none'
									})
									_self.isFail = true
									_self.complete = _self.colum*_self.colum-_self.bombs.length
						            // console.log('用户点击取消');
						        }
						    }
						});
					}else if(item.text == 0 && _self.complete < _self.colum*_self.colum-_self.bombs.length-8){
						_self.clearZero(id)
					}else{
						_self.complete =  _self.complete +1
					}
					
					this.$nextTick(async function(){
						if(_self.complete == _self.colum*_self.colum-_self.bombs.length){
							// 关闭定时器 初始化时间
							// await clearInterval(_self.timeId)
							await this.$store.commit("clearTimeId")
							
							// 提交成绩
							if(_self.isLogin){
								_self.grade.grade = _self.time
								_self.grade.player = _self.saolei.id
								_self.grade.model = _self.type
								
								await uni.request({
									url: utils.basicUrl+'/saoleiGrade',
									method: "POST",
									data: {
										..._self.grade
									},
									success: function(res) {
										if(res.data.code === 20000){
											uni.showToast({
												icon:"none",
												title:"上传成绩成功 ✧( •˓◞•̀ )  "
											})
										}else{
											_self.utils.requestFail(res)
											// uni.showToast({
											// 	icon:"none",
											// 	title: res.data
											// })
										}
									},
									fail: () => {
										uni.showToast({
											icon:"none",
											title:"网络错误(｡・`ω´･)",
											position:"center"
										})
									},
									complete() {
										
									}
								})
							}
							
							uni.showModal({
							    title: '挑战成功 ⁽⁽ଘ( ˊᵕˋ )ଓ⁾⁾ ',
							    content: '请选择是否继续',
								cancelText: "查看",
							    success: function (res) {
							        if (res.confirm) {
										_self.isFail = false
										_self.Init()
							        }else if (res.cancel) {
										// console.log('用户点击查看');
										// 清除所有遮罩
										_self.array.forEach(ar => {
											ar.type = 'none'
										})
										_self.$store.commit("clearTimeId")
										_self.complete = _self.colum*_self.colum-_self.bombs.length
									}
							    },complete: () => {
							    	_self.time = 0
							    }
							});
						}
					})
					
				})
			},
			
			// 批量清除为0的格子
			clearZero(i){
				
				if(_self.isFail){
					return
				}
				
				var target = []
				target.push(i)
				while(target.length > 0){
					// console.log(target)
					var id = parseInt(target.pop()) 
					var cl = parseInt(_self.colum)
					var flag = 0
					// 搜索8个方位角
					if( (id+1)%cl != 0 && (id+1) < cl*cl){
						if(_self.array[id+1].text == 0){
							if(_self.array[id+1].type == 'shade'){
								_self.array[id+1].type = 'none'
								target.push(id+1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id+1].type == 'shade' && _self.array[id+1].text != '炸'){
								_self.array[id+1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
						
					}
					if( id-1 >= 0 && id%cl != 0){
						if(_self.array[id-1].text == 0){
							if(_self.array[id-1].type == 'shade'){
								_self.array[id-1].type = 'none'
								target.push(id-1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id-1].type == 'shade' && _self.array[id-1].text != '炸'){
								_self.array[id-1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id-cl >= 0){
						if(_self.array[id-cl].text == 0){
							if(_self.array[id-cl].type == 'shade'){
								_self.array[id-cl].type = 'none'
								target.push(id-cl)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id-cl].type == 'shade' && _self.array[id-cl].text != '炸'){
								_self.array[id-cl].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id-cl+1 >= 0 && (id-cl+1)%cl != 0){
						if(_self.array[id-cl+1].text == 0){
							if(_self.array[id-cl+1].type == 'shade'){
								_self.array[id-cl+1].type = 'none'
								target.push(id-cl+1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id-cl+1].type == 'shade' && _self.array[id-cl+1].text != '炸'){
								_self.array[id-cl+1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id-cl-1 >= 0 && (id-cl)%cl != 0){
						if(_self.array[id-cl-1].text == 0){
							if(_self.array[id-cl-1].type == 'shade'){
								_self.array[id-cl-1].type = 'none'
								target.push(id-cl-1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id-cl-1].type == 'shade' && _self.array[id-cl-1].text != '炸'){
								_self.array[id-cl-1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id+cl < cl*cl){
						if(_self.array[id+cl].text == 0){
							if(_self.array[id+cl].type == 'shade'){
								_self.array[id+cl].type = 'none'
								target.push(id+cl)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id+cl].type == 'shade' && _self.array[id+cl].text != '炸'){
								_self.array[id+cl].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id+cl+1 < cl*cl && (id+cl+1)%cl != 0){
						if(_self.array[id+cl+1].text == 0){
							if(_self.array[id+cl+1].type == 'shade'){
								_self.array[id+cl+1].type = 'none'
								target.push(id+cl+1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id+cl+1].type == 'shade' && _self.array[id+cl+1].text != '炸'){
								_self.array[id+cl+1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					if( id+cl-1 < cl*cl && (id+cl)%cl != 0){
						if(_self.array[id+cl-1].text == 0){
							if(_self.array[id+cl-1].type == 'shade'){
								_self.array[id+cl-1].type = 'none'
								target.push(id+cl-1)
							}else{
								flag ++
							}
						}else{
							// 遇到边界了
							if(_self.array[id+cl-1].type == 'shade' && _self.array[id+cl-1].text != '炸'){
								_self.array[id+cl-1].type = 'none'
								flag ++
							}else{
								// 遇到炸弹了
								flag ++
							}
						}
					}
					
					if(flag == 8){
						// 8方均开
						var index = target.indexOf(id)
						target.splice(index,1)
					}
					
				}
				
				// 更新已完成的格子
				this.$nextTick(function(){
					_self.complete = 0
					_self.array.forEach(ar => {
						if(ar.type == 'none'){
							_self.complete ++
						}
					})
				})
				
			},
			removepop(id){
				this.$refs.message.remove(id)
			},
		}
	}
</script>

<style>
	@import url("index.css");
</style>
